#!/usr/bin/env python3
import os
import time
import subprocess
from datetime import datetime

# 配置部分
REMOTE = "vincentzyu@192.168.31.168:/home/vincentzyu/SSoftwareFiles/minecraft/paper-1.21.3-lobby/server/plugins/AuthMe"
MOUNT_POINT = "/home/zyu/SSoftwareFiles/sshfs_dir"
UID = "1001"
GID = "1001"

SSHFS_CMD = [
    "sshfs",
    REMOTE,
    MOUNT_POINT,
    "-o", "reconnect",
    "-o", "ServerAliveInterval=15",
    "-o", "ServerAliveCountMax=3",
    "-o", "idmap=user",
    f"-o", f"uid={UID},gid={GID}",
    "-o", "allow_other"
]

CHECK_INTERVAL = 30  # 每隔多少秒检查一次


# 日志颜色配置
COLORS = {
    "INFO": "\033[92m",   # 绿色
    "WARN": "\033[93m",   # 黄色
    "ERROR": "\033[91m",  # 红色
    "RESET": "\033[0m"    # 还原
}


def log(level, message):
    """通用日志输出函数"""
    now = datetime.now().strftime("%Y年%m月%d日-%H:%M:%S")
    color = COLORS.get(level, "")
    reset = COLORS["RESET"]
    print(f"{now} {color}[{level}] {message}{reset}")


def is_mounted():
    """检查挂载点是否已经挂载"""
    try:
        output = subprocess.check_output(["mount"]).decode()
        return MOUNT_POINT in output
    except Exception:
        return False


def mount():
    """执行挂载"""
    log("INFO", "尝试挂载 sshfs ...")
    try:
        # 先清理坏的挂载
        subprocess.call(["fusermount", "-uz", MOUNT_POINT], stderr=subprocess.DEVNULL)
        subprocess.call(["umount", "-l", MOUNT_POINT], stderr=subprocess.DEVNULL)
        # 确保目录存在
        os.makedirs(MOUNT_POINT, exist_ok=True)
        # 执行挂载
        subprocess.check_call(SSHFS_CMD)
        log("INFO", "挂载成功！")
    except subprocess.CalledProcessError as e:
        log("ERROR", f"挂载失败: {e}")


def main():
    while True:
        if not is_mounted():
            log("WARN", "挂载丢失，重新挂载中...")
            mount()
        else:
            log("INFO", "挂载正常。")
        time.sleep(CHECK_INTERVAL)


if __name__ == "__main__":
    main()
